package com.gcloud.mesh.dcs.chain.k8s;

import java.net.URL;

import org.jeecg.common.exception.MyBusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.gcloud.mesh.asset.service.ICloudResourceService;
import com.gcloud.mesh.config.DnsConfig;
import com.gcloud.mesh.dcs.chain.FilterChain;
import com.gcloud.mesh.dcs.chain.IMigrationStepChain;
import com.gcloud.mesh.framework.core.SpringUtil;
import com.gcloud.mesh.supplier.enums.SystemType;
import com.gcloud.mesh.utils.DnsUtil;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class UpdateDNSConfig implements IMigrationStepChain {

    @Autowired
    private ICloudResourceService cloudResourceService;

    @Override
    public void doExec(String schedulerJobId, String attach, FilterChain filterChain, IMigrationStepChain stepChain) {
        JSONObject jsonObject = JSONObject.parseObject(attach);
        String appId = jsonObject.getString("appId");
        String appName = jsonObject.getString("appName");
        String destUrl = jsonObject.getString("dstUrl");
        String schedulerModel = jsonObject.getString("schedulerModel");
        String destDatacenterId = jsonObject.getString("dstDatacenterId");
        String destNodeId = jsonObject.getString("dstNodeId");
        try {
            DnsConfig config = SpringUtil.getBean(DnsConfig.class);
            URL url = new URL(destUrl);
            DnsUtil.addAndRunDnsFile(config.getServer(), config.getDomain(), url.getHost());
            filterChain.doExec(schedulerJobId,attach,filterChain,stepChain);
        } catch (Exception e) {
            log.error("[schedule] 数据中心调度更改dnsnamespaceName{}", appName, e);
            throw new MyBusinessException(appName+"更新DNS配置失败"+"::"+e.getMessage());
        }
    }

    @Override
    public String chainType() {
        return SystemType.K8S.getName();
    }

    @Override
    public String chainName(String attach) {
        return "更新DNS配置信息";
    }

    @Override
    public int getOrder() {
        return 4;
    }
}
